package com.farah.lease.web.admin.custom.interceptor;

import com.farah.lease.common.login.LoginUserHolder;
import com.farah.lease.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author 不爱跑步的法拉韶
 * @Date 2024-06-24__14:16
 * @Description 拦截器
 **/
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    /**
     * 程序执行前拦截
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return 是否有效
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String token = request.getHeader("access-token");
       JwtUtil.parseToken(token);
       return true;
    }

    /**
     * 请求完成后删除ThreadLocal中的用户信息
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link HandlerMethod}) that started asynchronous
     * execution, for type and/or instance examination
     * @param ex any exception thrown on handler execution, if any; this does not
     * include exceptions that have been handled through an exception resolver
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
